package com.grantha.controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.grantha.util.DB;
import com.grantha.util.Util;

/**
 * Servlet implementation class BorrowerEntryServlet
 */
@WebServlet("/BorrowerEntryServlet")
public class BorrowerEntryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger log = Logger.getLogger(this.getClass());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    
        // TODO Auto-generated constructor stub
   

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
		
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		
		log.info("Servlet Stated");
		
		String patno = request.getParameter("serial");
        String name = request.getParameter("name");
        String sex = request.getParameter("jradiobutton1");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String designation = request.getParameter("designation");
        String moreinfo = request.getParameter("addi");
        String gurantername = request.getParameter("gname");
        String guranterphone = request.getParameter("gphone");
        String guranteraddress = request.getParameter("gaddress");
        
        log.info("patno="+patno);
		log.info("sex="+sex);
		log.info("phone="+phone);
		
		try {
			log .info("Serial checking");
	        ResultSet rs = DB.search("select * from patronregister where patno = ?",patno);
			if(rs.next()){
				log.info("patno exists");
				out.print(Util.sendJSONMessage(false, "patron serial already taken"));}
			else{
				DB.update("insert into patronregister (patno, name,sex, address,phone,designation,moreinfo,gurantername,guranterphone,guranteraddress) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",patno, name,sex, address,phone,designation,moreinfo,gurantername,guranterphone,guranteraddress );
				out.print(Util.sendJSONMessage(true, "Patron added successfully"));
				log.info("success");
			}
		} catch (Exception e) {
			out.print(Util.sendJSONMessage(false, "Error when adding patrons"));
			log.error("Error");
		}
        
		
		
	}

}
